package pl.nith.battleships.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

import pl.nith.battleships.managers.GameStateManager.GameState;
import pl.nith.battleships.managers.Manager;

public class Client extends Thread
{
	public boolean				isClientConnected	= false;

	private Socket				connection			= null;
	private BufferedReader		incoming			= null;
	private PrintWriter			outgoing			= null;

	private BattleshipProtocol	protocol			= new BattleshipProtocol();

	private String				fromServer			= null;

	public void sendMessage(String message)
	{
		outgoing.println(message);
	}

	@Override
	public void run()
	{
		try
		{
			connection = new Socket(InetAddress.getByName(Manager.getConfigFile().getProperty("hostIP")), 4444);

			if (connection.isConnected()
							&& Manager.getGMS().currentGameState == GameState.GAME_NOT_STARTED)
			{
				Manager.getGMS().currentGameState = GameState.CONNECTED;
				Manager.getMWV().getMainWindow().getPubBoardSurface().changeButtonToSetShips();
			}

			incoming = new BufferedReader(new InputStreamReader(
							connection.getInputStream()));
			outgoing = new PrintWriter(connection.getOutputStream(), true);

			while ((fromServer = incoming.readLine()) != null)
			{
				protocol.processCommand(fromServer);
				if (fromServer.equals("Bye.")) break;
			}

			outgoing.close();
			incoming.close();
			connection.close();
		}
		catch (IOException e)
		{
			System.err.println(e.getMessage());
		}
	}
}
